package com.share.payment.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.binarywang.wxpay.bean.result.WxPayOrderQueryResult;
import com.share.common.core.domain.R;
import com.share.common.core.exception.ServiceException;
import com.share.common.rabbit.constant.MqConst;
import com.share.common.rabbit.service.RabbitService;
import com.share.common.security.utils.SecurityUtils;
import com.share.order.api.RemoteOrderInfoService;
import com.share.order.domain.OrderInfo;
import com.share.payment.domain.PaymentInfo;
import com.share.payment.mapper.PaymentInfoMapper;
import com.share.payment.service.IPaymentInfoService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @author ZhouShuang
 * @version 17
 * @Title
 * @date 2025/10/25 上午8:54
 */
@Service
@RequiredArgsConstructor
public class PaymentInfoService extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements IPaymentInfoService {
    private final PaymentInfoMapper paymentInfoMapper;
    private final RemoteOrderInfoService remoteOrderInfoService;
    private final RabbitService rabbitService;

    /**
     * 添加订单
     *
     * @param orderNo
     * @return
     */
    @Override
    public PaymentInfo savePaymentInfo(String orderNo) {
        //1.通过订单编号查询支付记录是否存在
        PaymentInfo paymentInfo = paymentInfoMapper.selectOne(new LambdaQueryWrapper<PaymentInfo>().eq(PaymentInfo::getOrderNo, orderNo));
        //2如果支付记录不存在，则进行添加
        if (ObjectUtil.isEmpty(paymentInfo)) {
            // 3 远程调用:根据订单编号查询订单数据
            R<OrderInfo> orderInfoResult = remoteOrderInfoService.getByOrderNo(orderNo);
            if (R.FAIL == orderInfoResult.getCode()) {
                throw new ServiceException(orderInfoResult.getMsg());
            }
            OrderInfo orderInfo = orderInfoResult.getData();
            //添加数据
            paymentInfo = new PaymentInfo();
            paymentInfo.setUserId(orderInfo.getUserId());
            paymentInfo.setContent("共享充电宝租借");
            paymentInfo.setAmount(orderInfo.getTotalAmount());
            paymentInfo.setOrderNo(orderNo);
            paymentInfo.setPaymentStatus(0);
            paymentInfo.setCreateTime(new Date());
            paymentInfo.setUpdateTime(new Date());
            paymentInfo.setDelFlag("0");
            paymentInfo.setCreateBy(SecurityUtils.getUsername());
            paymentInfo.setUpdateBy(SecurityUtils.getUsername());
            paymentInfoMapper.insert(paymentInfo);
        }
        if (paymentInfo.getPaymentStatus() == 1) {
            throw new ServiceException("订单已关闭");
        }
        return paymentInfo;
    }

    /**
     * 修改支付记录状态
     *
     * @param wxPayOrderQueryResult
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updatePaymentStatus(WxPayOrderQueryResult wxPayOrderQueryResult) {
        PaymentInfo paymentInfo = paymentInfoMapper.
                selectOne(new LambdaQueryWrapper<PaymentInfo>().eq(PaymentInfo::getOrderNo, wxPayOrderQueryResult.getOutTradeNo()));
        //1.已支付，直接返回
        if (paymentInfo.getPaymentStatus() == 1) {
            return;
        }
        //更新支付信息
        paymentInfo.setPaymentStatus(1);
        paymentInfo.setOrderNo(wxPayOrderQueryResult.getOutTradeNo());
        paymentInfo.setTransactionId(wxPayOrderQueryResult.getTransactionId());
        paymentInfo.setCallbackTime(new Date());
        paymentInfo.setCallbackContent(com.alibaba.fastjson.JSON.toJSONString(wxPayOrderQueryResult));
        this.updateById(paymentInfo);

        //基于MQ通知订单系统，修改订单状态
        rabbitService.sendMessage(MqConst.EXCHANGE_PAYMENT_PAY, MqConst.ROUTING_PAYMENT_PAY, paymentInfo.getOrderNo());
    }
}
